<template>
  <el-dialog
    title="图片编辑"
    :visible.sync="visible"
    width="700px"
    :before-close="handleClose"
  >
    <div class="image-editor">
      <div class="editor-main">
        <img :src="imageData" ref="editorImage" class="editor-image" />
      </div>
      
      <div class="editor-tools">
        <el-button-group>
          <el-button @click="rotate(-90)">左旋转</el-button>
          <el-button @click="rotate(90)">右旋转</el-button>
          <el-button @click="reset">重置</el-button>
        </el-button-group>
        
        <div class="action-buttons">
          <el-button type="primary" @click="confirmEdit">确认</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'ImageEditor',
  
  props: {
    visible: Boolean,
    imageData: String
  },
  
  data() {
    return {
      rotation: 0
    }
  },
  
  methods: {
    rotate(degrees) {
      this.rotation += degrees
      this.applyRotation()
    },
    
    applyRotation() {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const img = this.$refs.editorImage
      
      if (this.rotation % 180 !== 0) {
        canvas.width = img.naturalHeight
        canvas.height = img.naturalWidth
      } else {
        canvas.width = img.naturalWidth
        canvas.height = img.naturalHeight
      }
      
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.translate(canvas.width / 2, canvas.height / 2)
      ctx.rotate(this.rotation * Math.PI / 180)
      ctx.drawImage(img, -img.naturalWidth / 2, -img.naturalHeight / 2)
      
      this.$emit('image-updated', canvas.toDataURL())
    },
    
    reset() {
      this.rotation = 0
      this.$emit('image-updated', this.imageData)
    },
    
    confirmEdit() {
      this.$emit('edit-confirm')
      this.handleClose()
    },
    
    handleClose() {
      this.rotation = 0
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style lang="scss" scoped>
.image-editor {
  .editor-main {
    text-align: center;
    margin-bottom: 20px;
    
    .editor-image {
      max-width: 100%;
      max-height: 400px;
      border: 1px solid #e6e8eb;
      border-radius: 4px;
    }
  }
  
  .editor-tools {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>